/**
 * Created by Administrator on 2017/6/23.
 */

$.fn.serializeObject = function(){
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            var tmp = o[this.name];
            o[this.name] = tmp+","+(this.value || '');
            /*if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            if($.trim(o[this.name]) == ''){
                o[this.name].push(this.value || '');
            }else{
                o[this.name].push(","+(this.value || ''));
            }*/
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

/**
 * 将$("#form").serializeArray()对象转成json对象
 * @param formValues
 * @returns {{}}
 */
function convertToJson(formValues) {
    var result = {};
    for(var formValue,j=0;j<formValues.length;j++) {
        formValue = formValues[j];
        var name = formValue.name;
        var value = formValue.value;
        if (name.indexOf('.') < 0) {
            result[name] = value;
            continue;
        } else {
            var simpleNames = name.split('.');
            // 构建命名空间
            var obj = result;
            for ( var i = 0; i < simpleNames.length - 1; i++) {
                var simpleName = simpleNames[i];
                if (simpleName.indexOf('[') < 0) {
                    if (obj[simpleName] == null) {
                        obj[simpleName] = {};
                    }
                    obj = obj[simpleName];
                } else { // 数组
                    // 分隔
                    var arrNames = simpleName.split('[');
                    var arrName = arrNames[0];
                    var arrIndex = parseInt(arrNames[1]);
                    if (obj[arrName] == null) {
                        obj[arrName] = []; // new Array();
                    }
                    obj = obj[arrName];
                    multiChooseArray = result[arrName];
                    if (obj[arrIndex] == null) {
                        obj[arrIndex] = {}; // new Object();
                    }
                    obj = obj[arrIndex];
                }
            }

            if(obj[simpleNames[simpleNames.length - 1]] ) {
                var temp = obj[simpleNames[simpleNames.length - 1]];
                obj[simpleNames[simpleNames.length - 1]] = temp;
            }else {
                obj[simpleNames[simpleNames.length - 1]] = value;
            }

        }
    }
    return result;
}